package com.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderAspect {

    private final Random random = new Random();

    /**
     * 1. 前置增强：在所有方法执行前输出信息
     */
    @Before("execution(* com.example.service.OrderService.*(..))")
    public void beforeAdvice() {
        System.out.println("👋 hello, 我是一个前置增强");
    }

    /**
     * 2. 后置增强：在add和delete方法执行后输出信息
     */
    @After("execution(* com.example.service.OrderService.add(..)) || execution(* com.example.service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("👋 bye, 我是一个后置增强");
    }

    /**
     * 3. 返回通知：获取方法返回值并输出
     */
    @AfterReturning(pointcut = "execution(* com.example.service.OrderService.*(..))", returning = "result")
    public void afterReturningAdvice(Object result) {
        if (result != null) {
            System.out.println("📊 方法返回值: " + result);
        } else {
            System.out.println("📊 方法执行完成，无返回值");
        }
    }

    /**
     * 4. 环绕通知：计算方法执行时间
     */
    @Around("execution(* com.example.service.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;

        String methodName = joinPoint.getSignature().getName();
        System.out.println("⏰ 方法 " + methodName + " 执行时间: " + executionTime + "ms");

        return result;
    }

    /**
     * 5. 权限检查：在add和delete方法执行前进行权限验证
     */
    @Before("execution(* com.example.service.OrderService.add(..)) || execution(* com.example.service.OrderService.delete(..))")
    public void checkPermission() {
        int permission = random.nextInt(2); // 生成0或1

        if (permission == 0) {
            System.out.println("✅ 权限验证通过");
        } else {
            System.out.println("❌ 权限验证失败，无操作权限");
            throw new SecurityException("权限不足，操作被拒绝");
        }
    }

    /**
     * 异常处理：当权限验证失败时捕获异常
     */
    @AfterThrowing(pointcut = "execution(* com.example.service.OrderService.*(..))", throwing = "ex")
    public void afterThrowingAdvice(SecurityException ex) {
        System.out.println("⚠️ 捕获到安全异常: " + ex.getMessage());
        System.out.println("🚫 操作被终止");
    }
}